using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;

public class SpeedCtrlMachine : StateMachineBehaviour
{
    [Header("PropertyField<<============")]
    //[SerializeField] private float playSpeed = 1;

    [Space(20)]
    [Header("DebugField<<===============")]
    [SerializeField] private float curNormalizedTime = 0;
    Animator anim;

    public float curSpeed = 0;
    private float lastSpeed;
    public int lay = 0;
    public float initStateTime = 0;


    public float CurNormalizedTime { get => curNormalizedTime; set => curNormalizedTime = value; }
    //public float PlaySpeed { get => playSpeed; set => playSpeed = value; }

    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, AnimatorControllerPlayable controller)
    {
        EventCenterManager.AddListener<float>(EventDefine.changeAnimSpeed, ChangeSpeed);
        anim = animator;
        lastSpeed = anim.speed;
        anim.speed = 0;
        curSpeed = 0;
        animator.Play("",lay,initStateTime);
    }

    public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, AnimatorControllerPlayable controller)
    {
        //animator.speed = PlaySpeed;
        CurNormalizedTime = stateInfo.normalizedTime;
        CurNormalizedTime = Mathf.Clamp01(CurNormalizedTime);
        CurNormalizedTime += curSpeed;
        CurNormalizedTime = Mathf.Clamp01(CurNormalizedTime);


        animator.Play("", lay, CurNormalizedTime);
    }

    public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, AnimatorControllerPlayable controller)
    {
        anim.speed = lastSpeed;
    }

    public void ChangeSpeed(float playSpeed)
    {
        curSpeed = playSpeed;
    }
}
